<template>
  <div id="box" style="height:100%;width:100%">
    <div id="terminal"></div>
  </div>
</template>

<script>
import { Terminal } from "xterm";
import { FitAddon } from 'xterm-addon-fit'
import { AttachAddon } from 'xterm-addon-attach'
import "xterm/css/xterm.css";
import "xterm/lib/xterm.js";

export default {
  data(){
    return {
      connectData:{
        operate:'connect',
        host: '116.63.132.188',//IP
        port: '22',//端口号
        username: 'root',//用户名
        password: 'Chen12138',
        cols: '',
        rows: ''
      },
      websock: '',
      fitAddon:'',
      term:''
    }
  },
  mounted() {
    // const box = document.getElementById('box');
    // let height = box.clientHeight;
    // let width = box.clientWidth;
    // this.connectData.rows = parseInt(height/18, 10);//18是字体高度,根据需要自己修改
    // this.connectData.cols = parseInt(width/9, 10);
    
  },
  methods:{
    initWebSocket(){ //初始化weosocket
      const wsuri = "ws://localhost:8088/webssh";
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen(){ //连接建立之后执行send方法发送数据
      this.websocketsend(JSON.stringify(this.connectData));
      this.initTerm();
    },
    websocketonerror(error){//连接建立失败重连
      this.term.write('Error: ' + error + '\r\n');
    },
    websocketonmessage(e){ //数据接收
      this.term.write(e.data);
    },
    websocketsend(data){//数据发送
      this.websock.send(data);
    },
    websocketclose(e){  //关闭
      console.log('断开连接',e);
    },
    initTerm(){
      const terminal = document.getElementById("terminal");
      
      const term = new Terminal({
        cursorBlink: true, // 光标闪烁
        cursorStyle: "block", // 光标样式  null | 'block' | 'underline' | 'bar'
        scrollback: 800, //回滚
        tabStopWidth: 8, //制表宽度
        screenKeys: true,
        fontSize: 18
      });

      const attachAddon = new AttachAddon(this.websock);
      const fitAddon = new FitAddon();
      term.loadAddon(attachAddon);
      term.loadAddon(fitAddon);
      term.open(terminal);
      fitAddon.fit();
      term.focus();
      this.term = term;

      // this.term.onData((data) => {
      //   //键盘输入时的回调函数
      //   this.websocketsend(JSON.stringify({"operate": "command", "command": data}));
      // });
      // this.term.write('Connecting...\r\n');
    }
  }
}
</script>

<style lang="less">
*{
  margin: 0;
  padding: 0;
}

html,body{
  font-size: 18px;
  width: 100%;
  height: 100%;
}
</style>